<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="addPermision({type:1,pid:''})">添加权限</el-button>
        </div>
        <!-- id通常是我们当前列表中独一无二的一个字段 -->
        <el-table :data="perList" border row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template #default="{row}">
              <el-button type="text" @click="addPermision({type:2,pid:row.id})">添加</el-button>
              <el-button type="text" @click="editPermission(row.id)">编辑</el-button>
              <el-button type="text" @click="delPermission(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <!-- 新增弹框 -->
    <add-permision
      ref="addPermision"
      :visible="visible"
      :type="type"
      :pid="pid"
      @close-dialog="closeDialog"
      @update-list="fetchList"
    />
  </div>
</template>

<script>
import { getPermissionList, delPermission } from '@/api/permission'
import transTree from '@/utils/transTree'
import AddPermision from './components/add-permission.vue'
export default {
  components: {
    AddPermision
  },
  data() {
    return {
      perList: [],
      visible: false,
      type: null,
      pid: ''
    }
  },
  mounted() {
    this.fetchList()
  },
  methods: {
    async fetchList() {
      const res = await getPermissionList()
      this.perList = transTree(res)
    },
    addPermision({ type, pid }) {
      this.visible = true
      this.type = type
      this.pid = pid
    },
    closeDialog() {
      this.visible = false
    },
    delPermission(id) {
      this.$confirm('确定要删除该权限吗?', '温馨提示').then(async() => {
        await delPermission(id)
        // 更新列表
        this.fetchList()
      }).catch(() => {
        console.log('取消')
      })
    },
    editPermission(id) {
      this.visible = true
      // 调用子组件中的getDetail方法并且传入id
      this.$refs.addPermision.getDetail(id)
    }
  }
}
</script>
